package com.lsh.payment.core.service.allinpay.impl;

import com.alibaba.fastjson.JSON;
import com.lsh.payment.api.model.basevo.QueryContent;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.model.payenum.PayStatus;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.service.payment.IPayQueryChannelService;
import com.lsh.payment.core.service.payment.builder.AllinQueryBuilder;
import com.lsh.payment.core.service.payment.builder.QueryDirector;
import com.lsh.payment.core.service.payment.impl.PayBaseService;
import com.lsh.payment.core.service.payment.impl.PayQueryBaseService;
import com.lsh.payment.core.strategy.vo.base.BasePayResponse;
import com.lsh.payment.core.strategy.query.QueryStrategyContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * Created by peter on 16/11/26.
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
@Transactional(readOnly = true)
public class AllinQueryServiceImpl implements IPayQueryChannelService {

    private static Logger logger = LoggerFactory.getLogger(PayQueryBaseService.class);

    @Autowired
    private PayBaseService payBaseService;

    @Autowired
    private QueryStrategyContext context;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QueryContent query(PayDeal payDeal) {

        logger.info("通联查询开始 {}" , JSON.toJSONString(payDeal));

        String trxid = payDeal.getChannelTransaction();
        Map<String, Object> params;
        if(StringUtils.isNotBlank(trxid) && trxid.length() > 5){
            params = Collections.<String, Object>singletonMap("channelId", payDeal.getChannelTransaction());
        }else{
            params = Collections.<String, Object>singletonMap("payPaymentNo", payDeal.getPayPaymentNo());
        }

//        QueryStrategyContext context = new QueryStrategyContext();
        BasePayResponse basePayResponse = context.queryPayStatusByParams(BusinessConstant.ALLINQUERY, params);

        AllinQueryBuilder allinQueryBuilder = new AllinQueryBuilder();
        QueryDirector director = new QueryDirector(allinQueryBuilder);
        director.queryParse(basePayResponse, payDeal);

        QueryContent content = allinQueryBuilder.getResult();

        if (content.getPayCode() != null) {
            int payCode = content.getPayCode();
            if (payCode == PayStatus.PAY_SUCCESS.getValue()) {
                logger.info("allin 查寻 修改支付结果");
                payBaseService.updPayDeal(allinQueryBuilder.getUpdatePaydeal(), payDeal);
            }
        }
        logger.info("通联查询结果 {}" , JSON.toJSONString(content));
        return content;

    }
}
